/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nanosl.norg.general.gui;

import com.nanosl.lib.db.Manager;
import com.nanosl.norg.ent.AddressType;
import com.nanosl.norg.util.NTopComponent;
import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.Collection;
import javax.swing.table.DefaultTableModel;
import org.netbeans.api.settings.ConvertAsProperties;
import org.netbeans.spi.actions.AbstractSavable;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.UndoRedo;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;
import org.openide.util.lookup.AbstractLookup;
import org.openide.util.lookup.InstanceContent;
import org.openide.windows.TopComponent;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//com.nanosl.credit.editor//AddressTypeEditor//EN",
        autostore = false)
@TopComponent.Description(
        preferredID = "AddressTypeEditorTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "com.nanosl.credit.editor.AddressTypeEditorTopComponent")
@ActionReference(path = "Menu/Editor", position = 6)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_AddressTypeEditorAction",
        preferredID = "AddressTypeEditorTopComponent")
@Messages({
    "CTL_AddressTypeEditorAction=AddressTypeEditor",
    "CTL_AddressTypeEditorTopComponent=AddressTypeEditor Window",
    "HINT_AddressTypeEditorTopComponent=This is a AddressTypeEditor window"
})
public final class AddressTypeEditorTopComponent extends NTopComponent{

    private DefaultTableModel addressTypeTableModel;

    public AddressTypeEditorTopComponent() {
        initComponents();
        addressTypeTableModel = (DefaultTableModel) addressTypeTable.getModel();
        setName(Bundle.CTL_AddressTypeEditorTopComponent());
        setToolTipText(Bundle.HINT_AddressTypeEditorTopComponent());
        instanceContent = new InstanceContent();
        associateLookup(new AbstractLookup(instanceContent));
        codeTextField.getDocument().addUndoableEditListener(UndoRedoManager);
        typeTextField.getDocument().addUndoableEditListener(UndoRedoManager);
        codeTextField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                modify();
            }
        });
        typeTextField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                modify();
            }
        });
    }

    private void fillAddressTypeTable() {
        addressTypeTableModel.setRowCount(0);
        Collection<AddressType> codeCollection = manager.find(AddressType.class);
        for (AddressType addressType : codeCollection) {
            Object[] row = {
                addressType,
                addressType.getType()};
            addressTypeTableModel.addRow(row);
        }
    }

    private void modify() {
        if (getLookup().lookup(AddressTypeSavable.class) == null) {
            instanceContent.add(new AddressTypeSavable());
        }
    }

    @Override
    public void componentOpened() {
//        result = WindowManager.getDefault().findTopComponent("EntityExplorerTopComponent").getLookup().lookupResult(AddressType.class);
//        result.addLookupListener(this);
//        resultChanged(new LookupEvent(result));
        fillAddressTypeTable();
        codeTextField.requestFocus();
    }

    @Override
    public void componentClosed() {
    }

    public void resetFields() {
        codeTextField.setText("");
        typeTextField.setText("");
        codeTextField.requestFocus();
    }

    @Override
    public UndoRedo getUndoRedo() {
        return UndoRedoManager;
    }

    private class AddressTypeSavable extends AbstractSavable {

        String code, type;

        AddressTypeSavable() {
            register();
        }

        @Override
        protected String findDisplayName() {
            code = codeTextField.getText();
            type = typeTextField.getText();
            return "( " + code + " ) " + type;
        }

        @Override
        protected void handleSave() throws IOException {

            code = codeTextField.getText().trim();
            type = typeTextField.getText().trim();
            if (code.equals("") || type.equals("")) {
                return;
            }
            NotifyDescriptor.Confirmation message = new NotifyDescriptor.Confirmation(
                    "Do you want to save \n ( " + code + " ) " + type + "?", NotifyDescriptor.OK_CANCEL_OPTION, NotifyDescriptor.QUESTION_MESSAGE);
            Object result = DialogDisplayer.getDefault().notify(message);
//When user clicks "Yes", indicating they really want to save,
//we need to disable the Save action,
//so that it will only be usable when the next change is made.
            if (NotifyDescriptor.YES_OPTION.equals(result)) {
                AddressType addressType = new AddressType(code);
                addressType.setType(type);
                manager.update(addressType);
                resetFields();
                fillAddressTypeTable();
                tc().instanceContent.remove(this);
                unregister();
            }
        }

        AddressTypeEditorTopComponent tc() {
            return AddressTypeEditorTopComponent.this;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof AddressTypeSavable) {
                AddressTypeSavable m = (AddressTypeSavable) obj;
                return tc() == m.tc();
            }
            return false;
        }

        @Override
        public int hashCode() {
            return tc().hashCode();
        }
    }
    private Lookup.Result result = null;
    private UndoRedo.Manager UndoRedoManager = new UndoRedo.Manager();
    private InstanceContent instanceContent;

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        codeTextField = new javax.swing.JTextField();
        typeTextField = new javax.swing.JTextField();
        clearButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        addressTypeTable = new javax.swing.JTable();

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(AddressTypeEditorTopComponent.class, "AddressTypeEditorTopComponent.jLabel1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(AddressTypeEditorTopComponent.class, "AddressTypeEditorTopComponent.jLabel2.text")); // NOI18N

        codeTextField.setText(org.openide.util.NbBundle.getMessage(AddressTypeEditorTopComponent.class, "AddressTypeEditorTopComponent.codeTextField.text")); // NOI18N
        codeTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                codeTextFieldActionPerformed(evt);
            }
        });

        typeTextField.setText(org.openide.util.NbBundle.getMessage(AddressTypeEditorTopComponent.class, "AddressTypeEditorTopComponent.typeTextField.text")); // NOI18N
        typeTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                typeTextFieldActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(clearButton, org.openide.util.NbBundle.getMessage(AddressTypeEditorTopComponent.class, "AddressTypeEditorTopComponent.clearButton.text")); // NOI18N
        clearButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(saveButton, org.openide.util.NbBundle.getMessage(AddressTypeEditorTopComponent.class, "AddressTypeEditorTopComponent.saveButton.text")); // NOI18N
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        addressTypeTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Code", "Type"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        addressTypeTable.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                addressTypeTableKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                addressTypeTableKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(addressTypeTable);
        if (addressTypeTable.getColumnModel().getColumnCount() > 0) {
            addressTypeTable.getColumnModel().getColumn(0).setResizable(false);
            addressTypeTable.getColumnModel().getColumn(0).setPreferredWidth(50);
            addressTypeTable.getColumnModel().getColumn(0).setHeaderValue(org.openide.util.NbBundle.getMessage(AddressTypeEditorTopComponent.class, "AddressTypeEditorTopComponent.addressTypeTable.columnModel.title0")); // NOI18N
            addressTypeTable.getColumnModel().getColumn(1).setResizable(false);
            addressTypeTable.getColumnModel().getColumn(1).setPreferredWidth(150);
            addressTypeTable.getColumnModel().getColumn(1).setHeaderValue(org.openide.util.NbBundle.getMessage(AddressTypeEditorTopComponent.class, "AddressTypeEditorTopComponent.addressTypeTable.columnModel.title1")); // NOI18N
        }

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 323, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(codeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(typeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(clearButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(saveButton))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {clearButton, saveButton});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(codeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(typeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(clearButton)
                    .addComponent(saveButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void codeTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_codeTextFieldActionPerformed
        String code = codeTextField.getText().trim();
        if (!code.equals("")) {
            AddressType addressType = Manager.getInstance().find(AddressType.class, code);
            typeTextField.setText(addressType != null ? addressType.getType() : "");
            codeTextField.setBackground(Color.WHITE);
            typeTextField.requestFocus();
        } else {
            errorField(codeTextField);
        }

    }//GEN-LAST:event_codeTextFieldActionPerformed

    private void typeTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_typeTextFieldActionPerformed
        if (isText(typeTextField.getText().trim())) {
            typeTextField.setBackground(Color.WHITE);
            try {
                new AddressTypeSavable().handleSave();
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        } else {
            errorField(typeTextField);
        }
    }//GEN-LAST:event_typeTextFieldActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        try {
            new AddressTypeSavable().handleSave();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearButtonActionPerformed
        resetFields();
    }//GEN-LAST:event_clearButtonActionPerformed

    private void addressTypeTableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_addressTypeTableKeyReleased
    }//GEN-LAST:event_addressTypeTableKeyReleased

    private void addressTypeTableKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_addressTypeTableKeyPressed
        if (evt.getKeyCode() == 127) {
            AddressType addressType = (AddressType) addressTypeTable.getValueAt(addressTypeTable.getSelectedRow(), 0);
            if (confirm("Are you sure to delete " + addressType + "?")) {
                manager.delete(AddressType.class, addressType.getCode());
                fillAddressTypeTable();
            }
        }
    }//GEN-LAST:event_addressTypeTableKeyPressed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable addressTypeTable;
    private javax.swing.JButton clearButton;
    private javax.swing.JTextField codeTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton saveButton;
    private javax.swing.JTextField typeTextField;
    // End of variables declaration//GEN-END:variables

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }
}
